package com.itheima.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MapperFactory<T> {
    private static SqlSessionFactory factory;

    static {
        try {
            InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //返回dao代理实现类对象
    public static <T> T getDaoInstance(Class<T> daoClass) {
        final SqlSession sqlSession = factory.openSession();//手动提交事务
        //通过框架动态生成dao接口代理对象
        final T t = sqlSession.getMapper(daoClass);

        //对dao接口代理对象，再次进行增强，让其支持事务管理
        T proxy_t =(T) Proxy.newProxyInstance(t.getClass().getClassLoader(), t.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object value = null;

                try {
                    //执行dao原来方法
                   value=method.invoke(t,args);
                    //成功：提交事务
                    sqlSession.commit();
                } catch (Exception e) {
                    //失败：回滚事务
                    sqlSession.rollback();
                    e.printStackTrace();
                } finally {
                    if (sqlSession != null) {
                        sqlSession.close();
                    }
                }

                return value;
            }
        });



        return proxy_t;

    }


}
